package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"

	"gitee.com/meilier/flower/platform"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

type platformOptions struct {
	kernelVersionHint string
	outputPath        string
	specPath          string
}

var platformOpts platformOptions

func newPlatformCmd() *cobra.Command {
	platformCmd := &cobra.Command{
		Use:     "platform [FLAGS]",
		Short:   "generate platform provider spec",
		Example: "flower platform --hint 4.18",
		RunE:    platformCommand,
	}

	platformCmd.PersistentFlags().StringVar(&platformOpts.kernelVersionHint, "hint", "", "kernel version hint used platform")
	platformCmd.PersistentFlags().StringVarP(&platformOpts.outputPath, "output", "o", "", "write spec file to output file")
	platformCmd.PersistentFlags().StringVarP(&platformOpts.specPath, "verify", "v", "", "verify platform spec")

	return platformCmd
}

func platformCommand(c *cobra.Command, args []string) error {
	if len(args) != 0 {
		return errors.New("no arguments needed here, please use flags")
	}

	spec, err := platform.GenerateSpec()
	if err != nil {
		return err
	}
	specString, err := json.Marshal(spec)
	if err != nil {
		return err
	}

	if platformOpts.outputPath == "" {
		fmt.Printf("%s\n", specString)
		return nil
	}

	if err := ioutil.WriteFile(platformOpts.outputPath, specString, 0644); err != nil {
		return err
	}
	return nil
}
